//
//  SelectFactoryViewController.m
//  Rail
//
//  Created by hychen on 2018/3/4.
//  Copyright © 2018年 Hychen. All rights reserved.
//

#import "SelectFactoryViewController.h"
#import "SelectFactoryFoldCellModel.h"
#import "SelectFactorySectionTableViewCell.h"
#import "SelectFactoryTableViewCell.h"
#import "SelectFactoryLineTableViewCell.h"
#import "FactoryDetailViewController.h"
#import "ObserverDeviceListViewController.h"

@interface SelectFactoryViewController ()
@property (nonatomic, strong) FactoryTreeModel *treeModel;
@end

@implementation SelectFactoryViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationItem addSimpleTitleView:@"选择工区"];
    [self.tableView.mj_header beginRefreshing];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)refreshData {
    BMWeakSelf
    [HttpRequest loadWorkareaListDataSuccess:^(FactoryTreeModel *object) {
        weakSelf.treeModel = object;
        [weakSelf setupTableViewData];
        [weakSelf.tableView reloadData];
        [weakSelf.tableView.mj_header endRefreshing];
    } failure:^(NSString *code, NSString *msg) {
        Show_SV_Msg(msg)
        [weakSelf.tableView.mj_header endRefreshing];
    }];
}

- (void)setupTableViewData {
    /*
     线路 --
     FactoryTreeLineModel(用于显示线路图)
     FactoryTreeAreaModel
     FactoryTreeAreaModel
     ...
     */
    NSMutableArray *dataArray = [NSMutableArray array];
    for (int i = 0; i < self.treeModel.list.count; ++i) {
        //Section折叠模型
        SelectFactoryFoldCellModel *secFoldModel = [SelectFactoryFoldCellModel new];
        secFoldModel.level = @"0";
        FactoryTreeLineModel *line = [self.treeModel.list objectAtIndexSafe:i];
        line.isSection = YES;
        secFoldModel.obj = line;
        secFoldModel.belowCount = 0;
        NSMutableArray *subArray = [NSMutableArray array];
        //线路Cell折叠模型
        FactoryTreeLineModel *lineCopy = line.copy;
        lineCopy.isSection = NO;
        SelectFactoryFoldCellModel *linePathFoldModel = [SelectFactoryFoldCellModel new];
        linePathFoldModel.level = @"0";
        linePathFoldModel.obj = lineCopy;
        linePathFoldModel.supermodel = secFoldModel;
        [subArray addObject:linePathFoldModel];
        
//        //默认工区折叠模型
//        FactoryTreeStationModel *station = line.station_list.firstObject;
//        if ([station isKindOfClass:[FactoryTreeStationModel class]] && station.area_list.count > 0) {
//            for (int j = 0; j < station.area_list.count; ++j) {
//                FactoryTreeAreaModel *model = [station.area_list objectAtIndexSafe:j];
//                SelectFactoryFoldCellModel *areaFoldModel = [SelectFactoryFoldCellModel new];
//                areaFoldModel.level = @"1";
//                areaFoldModel.obj = model;
//                areaFoldModel.supermodel = secFoldModel;
//                [subArray addObject:areaFoldModel];
//            }
//            secFoldModel.submodels = subArray;
//        }

        secFoldModel.submodels = subArray;
        [dataArray addObject:secFoldModel];
    }
    
    self.dataArray = dataArray;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SelectFactoryFoldCellModel *model = [self.dataArray objectAtIndex:indexPath.row];
    if ([model.obj isKindOfClass:[FactoryTreeLineModel class]]) {
        FactoryTreeLineModel *lineModel = (FactoryTreeLineModel *)model.obj;
        if (lineModel.isSection) {
            //sectionCell
            SelectFactorySectionTableViewCell *cell = [SelectFactorySectionTableViewCell cellWithInitStyleTableView:tableView class:[SelectFactorySectionTableViewCell class]];
            cell.model = model;
            return cell;
        }
        else {
            //linePathCell
            SelectFactoryLineTableViewCell *cell = [SelectFactoryLineTableViewCell cellWithInitStyleTableView:tableView class:[SelectFactoryLineTableViewCell class]];
            
            //点击站点/标段回调 -> 刷新数据源
            BMWeakSelf
            [cell setBlockClickButton:^(id obj, SelectFactoryFoldCellModel *cellFoldModel) {
                [weakSelf handleRefreshStationOrSectionWorkAreaDataWithLineModel:cellFoldModel clickObj:obj];
            }];
            
            cell.cellFoldModel = model;
            return cell;
        }
    }
    else if ([model.obj isKindOfClass:[FactoryTreeAreaModel class]]) {
        SelectFactoryTableViewCell *cell = [SelectFactoryTableViewCell cellWithTableView:tableView class:[SelectFactoryTableViewCell class]];
        cell.titleLabel.text = ((FactoryTreeAreaModel *)model.obj).area_name?:@"";
        return cell;
    }
    return [UITableViewCell new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    SelectFactoryFoldCellModel *model = [self.dataArray objectAtIndex:indexPath.row];
    if ([model.obj isKindOfClass:[FactoryTreeLineModel class]]) {
        FactoryTreeLineModel *lineModel = (FactoryTreeLineModel *)model.obj;
        if (lineModel.isSection) {
            //sectionCell
            return 55.f;
        }
        else {
            //linePathCell
            FactoryTreeLineModel *lineModel = (FactoryTreeLineModel *)model.obj;
            NSInteger count = 0;
            for (FactoryTreeStationModel *stationModel in lineModel.station_list) {
                count++;
                count += stationModel.section_list.count;
            }
            return [SelectFactoryLineTableViewCell heightForSelectFactoryLineCell:count];;
        }
    }
    else if ([model.obj isKindOfClass:[FactoryTreeAreaModel class]]) {
        return 44.f;
    }
    return 0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    SelectFactoryFoldCellModel *didSelectModel = [self.dataArray objectAtIndex:indexPath.row];
    
    if ([didSelectModel.obj isKindOfClass:[FactoryTreeAreaModel class]]) {
        FactoryTreeAreaModel *areamodel = (FactoryTreeAreaModel *)didSelectModel.obj;
        //工区
        if (self.style == SelectFactoryControllerStyleScanSelectFactory) {
            if (self.BlockCallBack) {
                self.BlockCallBack(areamodel.areaid, areamodel.area_name);
                [self.navigationController popViewControllerAnimated:YES];
            }
        }
        else if (self.style == SelectFactoryControllerStyleScanFactoryDetail) {
            FactoryDetailViewController *vc = [FactoryDetailViewController new];
            vc.areaid = areamodel.areaid;
            vc.navTitle = areamodel.area_name;
            [self.navigationController pushViewController:vc animated:YES];
        }
        else if (self.style == SelectFactoryControllerStyleScanSelectDevice || self.style == SelectFactoryControllerStylePictureInPictureSelectDevice) {
            ObserverDeviceListViewController *vc = [ObserverDeviceListViewController new];
            if (self.style == SelectFactoryControllerStylePictureInPictureSelectDevice) {
                vc.isPictureInPicture = YES;
            }
            vc.areaId = areamodel.areaid;
            //传空获取全部状态的设备
            vc.status = @"";
            vc.BlockCallBack = self.BlockSelectDeviceCallBack;
            [self.navigationController pushViewController:vc animated:YES];
        }

    }
    else if ([didSelectModel.obj isKindOfClass:[FactoryTreeLineModel class]]) {
        FactoryTreeLineModel *lineModel = (FactoryTreeLineModel *)didSelectModel.obj;
        if (lineModel.isSection) {
            //sectionCell
            SelectFactorySectionTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
            //箭头切换方向
            [cell clickEvent];
            [tableView beginUpdates];
            if (didSelectModel.belowCount == 0) {
                //展开
                NSArray *submodels = [didSelectModel open];
                NSIndexSet *indexes = [NSIndexSet indexSetWithIndexesInRange:((NSRange){indexPath.row + 1,submodels.count})];
                [self.dataArray insertObjects:submodels atIndexes:indexes];
                
                //Rows
                NSMutableArray *indexPaths = [NSMutableArray new];
                for (int i = 0; i < submodels.count; i++) {
                    NSIndexPath *insertIndexPath = [NSIndexPath indexPathForRow:(indexPath.row + 1 + i) inSection:indexPath.section];
                    [indexPaths addObject:insertIndexPath];
                }
                [tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationFade];
            }
            else {
                //收缩
                NSArray *submodels = [self.dataArray subarrayWithRange:((NSRange){indexPath.row + 1,didSelectModel.belowCount})];
                [didSelectModel closeWithSubmodels:submodels];
                [self.dataArray removeObjectsInArray:submodels];
                
                //Rows
                NSMutableArray *indexPaths = [NSMutableArray new];
                for (int i = 0; i < submodels.count; i++) {
                    NSIndexPath *insertIndexPath = [NSIndexPath indexPathForRow:(indexPath.row + 1 + i) inSection:indexPath.section];
                    [indexPaths addObject:insertIndexPath];
                }
                [tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationFade];
            }
            [tableView endUpdates];
        }
        else {
            //linePathCell
            return;
        }
    }
}

- (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath {
    SelectFactoryFoldCellModel *model = [self.dataArray objectAtIndex:indexPath.row];
    return [model.level integerValue];
}

- (void)handleRefreshStationOrSectionWorkAreaDataWithLineModel:(SelectFactoryFoldCellModel *)cellFoldModel clickObj:(id)obj {
    //父类折叠模型
    SelectFactoryFoldCellModel *superFoldModel = cellFoldModel.supermodel;

    NSArray *areaArray = nil;
    if ([obj isKindOfClass:[FactoryTreeStationModel class]]) {
        areaArray = ((FactoryTreeStationModel *)obj).area_list;
    }
    else if ([obj isKindOfClass:[FactoryTreeSectionModel class]]) {
        areaArray = ((FactoryTreeSectionModel *)obj).area_list;
    }
    //生成新的工区折叠模型数组
    NSMutableArray *subArray = [NSMutableArray array];
    for (int j = 0; j < areaArray.count; ++j) {
        FactoryTreeAreaModel *model = [areaArray objectAtIndexSafe:j];
        SelectFactoryFoldCellModel *areaFoldModel = [SelectFactoryFoldCellModel new];
        areaFoldModel.level = @"1";
        areaFoldModel.obj = model;
        areaFoldModel.supermodel = superFoldModel;
        [subArray addObject:areaFoldModel];
    }

    //获取线路index
    NSInteger index = -1;
    if ([self.dataArray containsObject:cellFoldModel]) {
        index = [self.dataArray indexOfObject:cellFoldModel];
    }
    
    if (index < 0) {
        return;
    }
    
    //移除已显示的工区
    NSMutableArray *indexPaths = [NSMutableArray new];
    if (superFoldModel.belowCount > 1) {
        NSArray *submodels = [self.dataArray subarrayWithRange:((NSRange){index + 1,superFoldModel.belowCount-1})];
        [superFoldModel closeWithSubmodels:submodels];
        [self.dataArray removeObjectsInArray:submodels];
        for (int i = 0; i < submodels.count; i++) {
            NSIndexPath *insertIndexPath = [NSIndexPath indexPathForRow:(index + 1 + i) inSection:0];
            [indexPaths addObject:insertIndexPath];
        }
        [self.tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationFade];
    }
    
    //添加将要显示的工区
    NSIndexSet *indexes = [NSIndexSet indexSetWithIndexesInRange:((NSRange){index + 1,subArray.count})];
    [self.dataArray insertObjects:subArray atIndexes:indexes];
    indexPaths = [NSMutableArray new];
    for (int i = 0; i < subArray.count; i++) {
        NSIndexPath *insertIndexPath = [NSIndexPath indexPathForRow:(index + 1 + i) inSection:0];
        [indexPaths addObject:insertIndexPath];
    }
    [self.tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationFade];

    //改变superFoldModel的数据源
    [subArray insertObject:cellFoldModel atIndex:0];
    superFoldModel.submodels = [NSMutableArray arrayWithArray:subArray];
    superFoldModel.belowCount = subArray.count;

}

#pragma mark - 返回
- (void)backBtnDidClick:(UIButton *)btn {
    if (self.style == SelectFactoryControllerStylePictureInPictureSelectDevice) {
        if (self.BlockCloseNavWithPictureInPictureStyle) {
            self.BlockCloseNavWithPictureInPictureStyle();
        }
    }
    else {
        [super backBtnDidClick:btn];
    }
}
@end
